# -*-Shell-script-*-
#
# mylibs This file contains functions to be used by custom
#        shell scripts.
#

## variables
# log_dir: save logs dir

## functions
# logger: print and save log
# cleaning: clean files or directories
# echo_line: print one char line
##

umask 022

# Set up a default search path.
PATH="/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/sbin:/usr/local/bin"
LANG="en_US.UTF-8"
export PATH LANG

# Set some variable
script_pid="$$"
script="$(basename $0)"
absdir="$(dirname $0)"

## To logs
[ -z ${log_dir:-} ] && log_dir="/tmp"
log_file="${log_dir}/${script%.*}.log"
log_err="${log_dir}/${script%.*}.err"
log_out="${log_dir}/${script%.*}.out"

# Format the output logs
function logger()
{
    local msg="$*"
    [ -z ${msg} ] && return 0

    local color_stat= end_color='\033[0m' out_file=

    if [[ "${msg}" =~ .*([eE][rR]{2}[oO]|[rR]|[fF][aA][iI][lL][eE][dD]).* ]];then
        color_stat='\033[1;31mError'
        out_file="${log_err}"
        elif [[ "${msg}" =~ .*([oO][kK]|[sS][uU][cC]{2}[eE][sS]{2}|[cC][oO][mM][pP][lL][eE][tT][eE]).* ]];then
        color_stat='\033[1;32mOK'
        out_file="${log_file}"
        elif [[ "${msg}" =~ .*[wW][aA][rR][nN][iI][nN][gG].* ]];then
        color_stat='\033[1;33mWarning'
        out_file="${log_file}"
    else
        color_stat='-'
        end_color=
        out_file="${log_file}"
    fi

    echo -e "$(date +%F\ %T) ${script} ${color_stat}${end_color} ${msg}"|tee -a "${out_file}"
}

# Clean files or directories
function cleaning () {
    logger "Cleaning [$1] ..."
    for f in $*;do
        [ -e "$f" ] && rm -rf "$f"
    done
}

# echo line length char
function echo_line () {
    local length=$1 chr="#"
    [[ "${length}" =~ ^[0-9]+$ ]] || length=$(tput cols)
    printf "${chr}%.s" $(seq -w ${length})
}
